var Module = angular.module('ngApp', ['ui.router']);
/*
* 路由
* */
Module.config(['$stateProvider',function ($stateProvider) {
    $stateProvider.
    state('register', {
        url:'/register',
        templateUrl: 'registerPage.html',
        controller: 'registerPageCtrl'
    }).state('subscription', {
        url:'/subscription',
        templateUrl: 'subscription.html',
        controller: 'subscriptionCtrl'
    }).state('queryCheckinRecord', {
        url:'/queryCheckinRecord',
        templateUrl: 'queryCheckinRecord.html',
        controller: 'recordCtrl'
    }).state('queryException', {
        url:'/queryException',
        templateUrl: 'queryException.html',
        controller: 'checkinExceptionCtrl'
    }).state('queryCCTVImages', {
        url:'/queryCCTVImages',
        templateUrl: 'queryCCTVImages.html',
        controller: 'cctvImgCtrl'
    });
}]);

Module.controller('mainCtrl',function ($rootScope,$scope,$http) {
	$rootScope.server="http://test.wechat.inuorui.com/api/data"
    var getQueryString = function (name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    };
    code = getQueryString("code");
    console.log(code);
    var getAccessToken = function(){
        $.ajax({
            type:"GET",
            url:"http://test.wechat.inuorui.com/api/user/accessToken?appId=wx751d208200afe9d0&code="+code,
            success:function (res) {
                console.log(res.reCode);
                console.log(res.reData.openid)
                $rootScope.openid=res.reData.openid;
            }
        });
    }
    getAccessToken();
})
/**
 * 查询异常记录
 */
Module.controller('checkinExceptionCtrl', function ($rootScope,$scope, $http) {
    $rootScope.title=" 船舶异常信息查询";
    $scope.selectedShip = -1;
    $scope.startTime = -1;
    $scope.endTime = -1;
    $scope.keyword = '';

    /**
     * 船舶基本信息
     */
    $scope.shipData = [];

    /**
     * 当前能查询到的数据
     * 数据结构：
     * String id;
     * long mmsi;
     * int code;
     * String msg;
     * Long createTime;
     * @type {array}
     */
    $scope.redata = [];
    $scope.pageNo = 0;
    /**
     * 查询条件下一共有多少条数据
     * @type {number}
     */
    $scope.totalElements = 0;


    $scope.modalContent = '';

    // 获取改变后的时间
    $('#start_datetime').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1
    }).on('changeDate', function (e) {
        console.log("changeDate");
        console.log(e.date.valueOf());
        $scope.startTime = e.date.valueOf();
    });
    $('#end_datetime').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1
    }).on('changeDate', function (e) {
        console.log("changeDate");
        console.log(e.date.valueOf());
        $scope.endTime = e.date.valueOf();
    });

    /**
     * 查询异常信息
     */
    $scope.queryException = function () {
        /**
         * 每页有多少条记录
         * @type {pageNo}
         */
        var pageSize = 5;
        $scope.totalElements = 20;
         $http({
             method: "get",
             url: $rootScope.server + "/checkIn/exception/ship",
             params: {
                 "mmsi": $scope.selectedShip,
                 "startTime": $scope.startTime,
                 "endTime": $scope.endTime,
             }
         }).then(function (res) {
             if (res.data.reMsg === 'SUCCESS') {
                 $scope.redata = res.data.reData.content;
                 for (var index in $scope.redata){
                     $scope.redata[index].shipName = $scope.formatShipName($scope.redata[index].mmsi);
                 }
                 if ($scope.redata === null || $scope.redata.length === 0) {
                     alert("没有查询到相关数据，请稍后再试");
                 }
                 $scope.states = res.data.reData.content;
                 $scope.totalPages = res.data.reData.totalPages;
             }
             else {
                 alert("服务器异常，请稍后再试");
             }
         }).catch(function (e) {
             console.error(e);
             alert("网络异常，请检查网络后，再试");
         });

    };

    /**
     * 获取全部船舶信息
     */
    $scope.queryShips = function () {
        $http({
            method: "get",
            url: $rootScope.server + "/checkIn/ship",

        }).then(function (res) {
            if (res.data.reMsg === 'SUCCESS') {
                $scope.shipData= res.data.reData;
                $scope.shipData[0] = {mmsi:-1,name:'全部船舶'};
                if ($scope.shipData === null || $scope.shipData.length === 0) {
                    alert("没有查询到相关数据，请稍后再试");
                }
            }
            else {
                alert("服务器异常，请稍后再试");
            }
        }).catch(function (e) {
            console.error(e);
            alert("网络异常，请检查网络后，再试");
        });
    }

    /**
     * 查询更多数据
     */
    $scope.queryMore = function () {
        console.log('more');
        $scope.pageNo += 1;
        $scope.queryException();
    }

    /**
     * 根据条件查询
     */
    $scope.queryByCondition = function () {
        $scope.pageNo = 0;
        $scope.redata = [];
        $scope.queryException();
    }

    /**
     * 根据mmsi获取对应的船名
     */
    $scope.formatShipName = function (mmsi) {
        for (var index in $scope.shipData){
            if($scope.shipData[index].mmsi === mmsi){
                return $scope.shipData[index].name;
            }
        }
    }

    /**
     * 格式化详细内容
     * @param msg
     * @returns {string}
     */
    $scope.formatMsg = function (msg) {
        if (msg && msg.length > 5) {
            return msg.substr(0, 5) + '...';
        }
        return msg;
    }

    $scope.detailModal = function (item) {
        $scope.modalContent = item.msg;
    }

    /**
     * 初始化
     */
    $scope.init = function () {
        $scope.queryShips();
        $scope.queryException();
    }

    $scope.init();


});

/**
 * 订阅设置
 */
Module.controller('subscriptionCtrl', function ($rootScope,$scope, $http) {
    $rootScope.title="船舶信息订阅推送";

    /**
     * 船舶基本信息
     */

    $scope.redata = [];

    $scope.subInfo = {
        openid: -1,
        mmsi: -1,
        exception: false,
        cctvImg: false
    };

    /**
     * 查询订阅信息
     */
    $scope.querySubscription = function () {

         $http({
             method: "get",
             url: $rootScope.server + "/checkIn/wechat/subscription/user",
             params: {
                 "openId":$rootScope.openid
             }
         }).then(function (res) {
             if (res.data.reMsg === 'SUCCESS') {
                 $scope.redata = res.data.reData;
                 console.log(res.data.reData)
                 if ($scope.redata === null || $scope.redata.length === 0) {
                     alert("没有查询到相关数据，请稍后再试");
                 }
             }
             else {
                 alert("服务器异常，请稍后再试");
             }
         }).catch(function (e) {
             console.error(e);
             alert("网络异常，请检查网络后，再试");
         });
    };

    $scope.activeClass = function (prop) {
        if (prop) {
            return 'btn-info active'
        }
        return 'btn-default';
    };

    $scope.subException = function (item) {
        item.exception = !item.exception;
        $scope.subInfo = item;
        $http({
            method: "get",
            url: $rootScope.server + "/checkIn/wechat/subscription/set",
            params: {
                "openId":$rootScope.openid,
                "mmsi":$scope.subInfo.mmsi,
                "subscription":1,
                "state":$scope.booleanToInt($scope.subInfo.exception),
            }
        }).then(function (res) {
            if (res.data.reMsg === 'SUCCESS') {

            }
            else {
                alert("服务器异常，请稍后再试");
            }
        }).catch(function (e) {
            console.error(e);
            alert("网络异常，请检查网络后，再试");
        });
        console.log($scope.subInfo)
    };


    $scope.subCCTVImg = function (item) {
        item.cctvImg = !item.cctvImg;
        $scope.subInfo = item;
        $http({
            method: "get",
            url: $rootScope.server + "/checkIn/wechat/subscription/set",
            params: {
                "openId":$rootScope.openid,
                "mmsi":$scope.subInfo.mmsi,
                "subscription":2,
                "state":$scope.booleanToInt($scope.subInfo.cctvImg),
            }
        }).then(function (res) {
            if (res.data.reMsg === 'SUCCESS') {

            }
            else {
                alert("服务器异常，请稍后再试");
            }
        }).catch(function (e) {
            console.error(e);
            alert("网络异常，请检查网络后，再试");
        });
        console.log($scope.subInfo)
    };
    $scope.booleanToInt = function(state) {
        if (state) {
            return 1
        }
        return 0
    }
    /**
     * 获取全部船舶信息
     */
    $scope.queryShips = function () {
        $http({
            method: "get",
            url: $rootScope.server + "/checkIn/ship",

        }).then(function (res) {
            if (res.data.reMsg === 'SUCCESS') {
                $scope.shipData[0] = {mmsi:-1,name:'全部船舶',notify:0,shipmail:''};
                $scope.shipData= $scope.shipData.concat(res.data.reData);
                if ($scope.shipData === null || $scope.shipData.length === 0) {
                    alert("没有查询到相关数据，请稍后再试");
                }
            }
            else {
                alert("服务器异常，请稍后再试");
            }
        }).catch(function (e) {
            console.error(e);
            alert("网络异常，请检查网络后，再试");
        });
    }
    /**
     * 根据mmsi获取对应的船名
     */
    $scope.formatShipName = function (mmsi) {
        for (var index in $scope.shipData){
            if($scope.shipData[index].mmsi === mmsi){
                return $scope.shipData[index].name;
            }
        }
        return '没有匹配到船名'
    }

    /**
     * 初始化
     */
    $scope.init = function () {

        $scope.querySubscription();
    }

    $scope.init();


})

/**
 * cctv 图像查询
 */
Module.controller('cctvImgCtrl', function ($rootScope,$scope, $http) {
    $rootScope.title="船舶CCTV图片查询";
    $scope.selectedShip = -1;
    $scope.startTime = -1;
    $scope.endTime = -1;
    $scope.keyword = '';

    /**
     * 船舶基本信息
     */
    $scope.shipData = [];

    $scope.redata = [];
    $scope.pageNo = 0;
    /**
     * 查询条件下一共有多少条数据
     * @type {number}
     */
    $scope.totalElements = 0;

    $scope.modalContent = '';

    // 获取改变后的时间
    $('#start_datetime').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1
    }).on('changeDate', function (e) {
        console.log("changeDate");
        console.log(e.date.valueOf());
        $scope.startTime = e.date.valueOf();
    });
    $('#end_datetime').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1
    }).on('changeDate', function (e) {
        console.log("changeDate");
        console.log(e.date.valueOf());
        $scope.endTime = e.date.valueOf();
    });

    $scope.detailModal = function (item) {
        console.log('modal');
        $scope.modalContent = "http://192.168.1.108:19797/checkIn/cctv/image?name="+item.imageName;
    }

    /**
     * 查询cctv信息
     */
    $scope.queryCCTVImg = function () {
        /**
         * 每页有多少条记录
         * @type {pageNo}
         */
        var pageSize = 5;
        $scope.totalElements = 20;
         $http({
             method: "get",
             url: $rootScope.server + "/checkIn/cctv/record",
             params: {
                 "mmsi": $scope.selectedShip,
                 "startTime": $scope.startTime,
                 "endTime": $scope.endTime,
                 "page": $scope.pageNo,
                 "pageSize": 10
             }
         }).then(function (res) {
             if (res.data.reMsg === 'SUCCESS') {
                 $scope.redata = res.data.reData.content;
                 if ($scope.redata === null || $scope.redata.length === 0) {
                     alert("没有查询到相关数据，请稍后再试");
                 }
             }
             else {
                 alert("服务器异常，请稍后再试");
             }
         }).catch(function (e) {
             console.error(e);
             alert("网络异常，请检查网络后，再试");
         });
    };

    /**
     * 获取全部船舶信息
     */
    $scope.queryShips = function () {
        $http({
            method: "get",
            url: $rootScope.server + "/checkIn/ship",

        }).then(function (res) {
            if (res.data.reMsg === 'SUCCESS') {
                $scope.shipData[0] = {mmsi:-1,name:'全部船舶',notify:0,shipmail:''};
                $scope.shipData= $scope.shipData.concat(res.data.reData);
                if ($scope.shipData === null || $scope.shipData.length === 0) {
                    alert("没有查询到相关数据，请稍后再试");
                }
            }
            else {
                alert("服务器异常，请稍后再试");
            }
        }).catch(function (e) {
            console.error(e);
            alert("网络异常，请检查网络后，再试");
        });
    }

    /**
     * 查询更多数据
     */
    $scope.queryMore = function () {
        console.log('more');
        $scope.pageNo += 1;
        $scope.queryCCTVImg();
    }

    /**
     * 根据条件查询
     */
    $scope.queryByCondition = function () {
        $scope.pageNo = 0;
        $scope.redata = [];
        $scope.queryCCTVImg();
    }

    /**
     * 根据mmsi获取对应的船名
     */
    $scope.formatShipName = function (mmsi) {
        for (var index in $scope.shipData){
            if($scope.shipData[index].mmsi === mmsi){
                return $scope.shipData[index].name;
            }
        }
        return '没有匹配到船名'
    }

    /**
     * 初始化
     */
    $scope.init = function () {
        $scope.queryShips();
        $scope.queryCCTVImg();
    }

    $scope.init();


});


/**
 * 签到记录查询
 */
Module.controller('recordCtrl', function ($rootScope,$scope, $http) {
    $rootScope.title="船舶签到信息查询";
    $scope.selectedShip =-1;
    $scope.startTime = -1;
    $scope.endTime = -1;
    $scope.keyword = '';

    /**
     * 船舶基本信息
     */
    $scope.shipData = [];

    $scope.redata = [];
    $scope.pageNo = 0;
    /**
     * 查询条件下一共有多少条数据
     * @type {number}
     */
    $scope.totalElements = 0;


    $scope.modalContent = '';

    // 获取改变后的时间
    $('#start_datetime').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1
    }).on('changeDate', function (e) {
        console.log("changeDate");
        console.log(e.date.valueOf());
        $scope.startTime = e.date.valueOf();
    });
    $('#end_datetime').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: true,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1
    }).on('changeDate', function (e) {
        console.log("changeDate");
        console.log(e.date.valueOf());
        $scope.endTime = e.date.valueOf();
    });

    /**
     * 查询异常信息
     */
    $scope.queryRecord = function () {
        /**
         * 每页有多少条记录
         * @type {pageNo}
         */
        var pageSize = 5;
        $scope.totalElements = 20;
         $http({
             method: "get",
             url: $rootScope.server + "/checkIn/record/queryByPaged/",
             params: {
                 "mmsi": $scope.selectedShip,
                 "sailorNo": -1,
                 "startTime": $scope.startTime,
                 "endTime": $scope.endTime,
                 "page": $scope.pageNo,
                 "pageSize": 10
             }
         }).then(function (res) {
             if (res.data.reMsg === 'SUCCESS') {
                 $scope.redata = res.data.reData.content;
                 for (var index in $scope.redata){
                     $scope.redata[index].shipName = $scope.formatShipName($scope.redata[index].mmsi);
                 }
                 if ($scope.redata === null || $scope.redata.length === 0) {
                     alert("没有查询到相关数据，请稍后再试");
                 }
                 $scope.totalPages = res.data.reData.totalPages;
             }
             else {
                 alert("服务器异常，请稍后再试");
             }
         }).catch(function (e) {
             console.error(e);
             alert("网络异常，请检查网络后，再试");
         });
    };

    $scope.detailModal = function (item) {
        $scope.modalContent = item.remark;
    }

    /**
     * 调API获取全部船舶信息到$scope.shipData
     */
    $scope.queryShips = function () {
        $http({
                 method: "get",
                 url: $rootScope.server + "/checkIn/ship/",

             }).then(function (res) {
                 if (res.data.reMsg === 'SUCCESS') {
                     $scope.shipData[0] = {mmsi:-1,name:'全部船舶'};
                     $scope.shipData= $scope.shipData.concat(res.data.reData);
                     if ($scope.shipData === null || $scope.shipData.length === 0) {
                         alert("没有查询到相关数据，请稍后再试");
                     }
                 }
                 else {
                     alert("服务器异常，请稍后再试");
                 }
             }).catch(function (e) {
                 console.error(e);
                 alert("网络异常，请检查网络后，再试");
             });
    }

    /**
     * 查询更多数据
     */
    $scope.queryMore = function () {
        console.log('more');
        $scope.pageNo += 1;
        $scope.queryRecord();
    }

    /**
     * 根据条件查询
     */
    $scope.queryByCondition = function () {
        $scope.pageNo = 0;
        $scope.redata = [];
        $scope.queryRecord();
    }

    /**
     * 根据mmsi获取对应的船名
     */
    $scope.formatShipName = function (mmsi) {
        for (var index in $scope.shipData){
            if($scope.shipData[index].mmsi === mmsi){
                return $scope.shipData[index].name;
            }
        }
    }
    $scope.formatMsg = function (msg) {
        if (msg && msg.length > 5) {
            return msg.substr(0, 5) + '...';
        }
        return msg;
    }
    $scope.formatState= function(state){
        if (state === 11){
            return '未签到'
        }
        return state
    }
    $scope.update= function(){
        console.log($scope.selectedShip)
    }
    /**
     * 初始化
     */
    $scope.init = function () {
        $scope.queryShips();
        $scope.queryRecord();
    }

    $scope.init();


});

/*
* 用户注册
* */
Module.controller('registerPageCtrl',function($rootScope,$scope,$http,$log){

    /*
    * 用户审核信息
    * */
    $scope.userData = {company:'HHM Law Firm',department:'技术部',name:'甘辉南',phone:13770480191,identifier:320802198607308561};
    $scope.reMsg = '';
    $scope.repeatedData = '';//手机号和身份证号重复
    $scope.navContentArray = ['登陆成功','创建账户','审核进行中','审核失败'];
    $scope.stateMsgArray = ['','您还不是正式用户，请注册以获取更多服务','您的审核正在进行中，请耐心等待','您的审核未能通过，请更改后重试'];

    $scope.userState = 1;//用户状态
    $scope.redata ={};//初始化返回信息
    $scope.stateMsg = '';
    $rootScope.title=$scope.navContentArray[$scope.userState];
    /*
    * 用户提交失败重新输入并在对应输入框按下键盘时，隐藏提示
    * */
    $scope.hide0 = function(){
        if($scope.reMsg === 'REPEATED' && $scope.repeatedData === 'company'){
            $("#repeatMsg").css("display","none");
        }
    };
    $scope.hide1 = function(){
        if($scope.reMsg === 'REPEATED' && $scope.repeatedData === 'department'){
            $("#repeatMsg").css("display","none");
        }
    };
    $scope.hide2 = function(){
        if($scope.reMsg === 'REPEATED' && $scope.repeatedData === 'name'){
            $("#repeatMsg").css("display","none");
        }
    };
    $scope.hide3 = function(){
        if($scope.reMsg === 'REPEATED' && $scope.repeatedData === 'phone'){
            $("#repeatMsg").css("display","none");
        }
    };
    $scope.hide4 = function(){
        if($scope.reMsg === 'REPEATED' && $scope.repeatedData === 'identifier'){
            $("#repeatMsg").css("display","none");
        }
    };
    /*
    * 确认提交
    * */
    $scope.jsonBody={
        openId:$rootScope.openid,
        state:0,
        createTimeStamp:0,
        company:$scope.userData.company,
        department: $scope.userData.department,
        realName: $scope.userData.name,
        mobile: $scope.userData.phone,
        ident: $scope.userData.identifier,
    }
    $scope.ok = function(){
        $http({
             method: "post",
             url: $rootScope.server + "/checkIn/wechat/user/save",
             data:angular.toJson($scope.jsonBody),
             header:{'Content-Type':'application/json;charset=UTF-8'}
         }).then(function (res) {
             if (res.data.reMsg === 'SUCCESS') {
                 $scope.reMsg = res.data.reMsg;
             }
              else if(res.data.reMsg === 'REPEATED') {
                  $scope.reMsg = res.data.reMsg;
                  $scope.repeatedData = res.data.reData.repeatedData
              }
             else {
                 alert("服务器异常，请稍后再试");
             }
         }).catch(function (e) {
             console.error(e);
             alert("网络异常，请检查网络后，再试");
        });
    };

    $('#submitModal').on('show.bs.modal',function () {
        console.log('modal is opended');
        $scope.reMsg = null;
        $scope.repeatedData = null;
    });


    $scope.init = function () {
        $http({
             method: "get",
             url: $rootScope.server + "/checkIn/wechat/user",
             params: {
                 "openId":$rootScope.openid,
             }
         }).then(function (res) {
             if (res.data.reData.state == -1) {
                  $scope.redata = res.data.reData
                  $scope.userState = 0;
             }
              else if(res.data.reData != -1) {
                  $scope.userState = 1;
              }
             else {
                 alert("服务器异常，请稍后再试");
             }
         }).catch(function (e) {
             console.error(e);
             alert("网络异常，请检查网络后，再试");
        });
        $scope.stateMsg = $scope.stateMsgArray[$scope.userState];
    };
    $scope.init();

});
